//
//  LBRPageEventEmitterModule.m
//  LBReact
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBRPageEventEmitterModule.h"

NSString *const LBPageLifeCycleNotification = @"LBPageLifeCycleNotification";
NSString *const LBPageLifeCycleEvent  = @"LifeCycleEvent";

#define LBPageLifeCycleSendNotification(moduleId, method) if (moduleId) { \
    [[NSNotificationCenter defaultCenter] postNotificationName:LBPageLifeCycleNotification \
                                                        object:self \
                                                      userInfo:@{ \
                                                                 @"moduleId": moduleId, \
                                                                 @"method": method \
                                                                 }]; \
    }

@implementation LBRPageEventEmitterModule

RCT_EXPORT_MODULE(pageEventEmitter)

- (NSArray<NSString *> *)supportedEvents {
  return @[LBPageLifeCycleEvent];
}


- (void)startObserving {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleLifeCycleNotification:)
                                                 name:LBPageLifeCycleNotification
                                               object:nil];
    [super startObserving];
}

- (void)stopObserving {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super stopObserving];
}

- (void)handleLifeCycleNotification:(NSNotification *)notification {
  [self sendEventWithName:LBPageLifeCycleEvent
                     body:[notification userInfo]];
}

+ (void)sendViewWillAppearEvent:(NSString *)moduleId {
    LBPageLifeCycleSendNotification(moduleId, @"viewWillAppear")
}

+ (void)sendViewWillDisappearEvent:(NSString *)moduleId {
    LBPageLifeCycleSendNotification(moduleId, @"viewWillDisappear")
}

+ (void)sendDeallocEvent:(NSString *)moduleId {
    LBPageLifeCycleSendNotification(moduleId, @"dealloc")
}

@end
